package client;

import java.io.*;
import java.math.RoundingMode;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Client {
	/*
	this class is a client which connects with server
	it can get the list including all file in server and
	can get one file from server
	 */
	public void connect(String command) {
		/*
		this method connects with server and execute command
		"list" and "get <filename>"
		 */
		try {

			// connect with server
			Socket socket = new Socket( "localhost", 8888 );
			// reader and writer from server
			PrintWriter writer = new PrintWriter( socket.getOutputStream(), true );
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			if (command.compareTo("list")==0){
				// list command
				writer.println("list");
				String msg;
				while((msg=reader.readLine())!=null){
					System.out.println(msg);
				}
				socket.close();
			}
			else{
				writer.println(command);
				String msg = reader.readLine();
				if (msg.compareTo("find it")==0){
					DataInputStream dis = new DataInputStream(socket.getInputStream());
					// 文件名和长度
					String fileName = dis.readUTF();
					long fileLength = dis.readLong();
					String path = System.getProperty("user.dir");
					File directory = new File(path);

					if(!directory.exists()) {
						//create dir
						directory.mkdir();
					}

					File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
					FileOutputStream fos = new FileOutputStream(file);

					//receive file
					byte[] bytes = new byte[1024];
					int length = 0;
					while((length = dis.read(bytes, 0, bytes.length)) != -1) {
						fos.write(bytes, 0, length);
						fos.flush();
					}
					System.out.println("======== success [File Name: " + fileName + "] [Size: " + getFormatFileSize(fileLength) + "] ========");
				}
				else{
					System.out.println(msg);
				}
			}
		}
		catch( IOException e ) {
			System.out.println( e );
		}
	}

	private String getFormatFileSize(long length) {
		/*
		set a format to show the file size
		 */
		DecimalFormat df;
		df = new DecimalFormat("#0.0");
		df.setRoundingMode(RoundingMode.HALF_UP);
		df.setMinimumFractionDigits(1);
		df.setMaximumFractionDigits(1);
		double size = ((double) length) / (1 << 30);
		if(size >= 1) {
			return df.format(size) + "GB";
		}
		size = ((double) length) / (1 << 20);
		if(size >= 1) {
			return df.format(size) + "MB";
		}
		size = ((double) length) / (1 << 10);
		if(size >= 1) {
			return df.format(size) + "KB";
		}
		return length + "B";
	}

	public static void main(String[] args) {
		/*
		run the client
		 */
		Client client = new Client();
		if (args.length==0){
			System.out.println("no command");
			return;
		}
		if (args.length>2){
			System.out.println("Error command.");
			return;
		}
		if (args.length==2){
			if (args[0].compareTo("get")!=0){
				System.out.println("Error command.");
				return;
			}
			else {
				args[0] = args[0] + " " + args[1];
			}
		}
		else if (args[0].compareTo("list")!=0){
			System.out.println("Error command.");
			return;
		}
		client.connect(args[0]);
	}
}